<script lang="ts" setup>
import {onMounted, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ArrowDown, Shop, User} from '@element-plus/icons-vue'
import http from '@/request/Http'
import {eventBus} from '@/eventBus.js'

const router = useRouter()
const activeMenu = ref('dashboard')

// 当前用户实体
const userInfo = ref({
  name: '',
  avatar: ''
})

//判断用户信息是否存在
if (!userInfo.value || !userInfo.value.name) {
  // 如果用户信息不存在，使用默认值
  userInfo.value = {
    name: '未登录',
    avatar: 'https://wen-gloupfive.oss-cn-hangzhou.aliyuncs.com/KXxBxTLBk8KLhWkkcf2v.jfif'
  }
}

// 从后端获取用户信息
const fetchUserInfo = async () => {
  // 获取存储的token字符串
  const tokenString = sessionStorage.getItem('token')

  // 检查是否存在token
  if (!tokenString || tokenString === 'null' || tokenString === 'undefined') {
    // 设置默认用户信息
    userInfo.value = {
      name: '未登录',
      avatar: 'https://wen-gloupfive.oss-cn-hangzhou.aliyuncs.com/EzJt5vBxxozU3Eevc97S.png'
    }
    return
  }
  try {
    // 发送 token 获取用户信息
    const response = await http.get('/user/getUserInfo', {
      headers: {
        'token': tokenString
      }
    }).then(res => res)
    const result = response
    // 检查业务逻辑是否成功
    if (result.code === 200) { // 假设200表示成功
      const userData = result.data

      //判断是否有图片
      if (!userData.avatar || userData.avatar === 'null' || userData.avatar === 'undefined') {
        // 如果用户信息不存在，使用默认值
        userData.avatar = 'https://wen-gloupfive.oss-cn-hangzhou.aliyuncs.com/EzJt5vBxxozU3Eevc97S.png'
      }
      // 更新用户信息
      userInfo.value = {
        name: userData.username,
        avatar: userData.avatar
      }
      return userData
    } else {
      // 设置默认用户信息
      userInfo.value = {
        name: '未登录',
        avatar: 'https://wen-gloupfive.oss-cn-hangzhou.aliyuncs.com/EzJt5vBxxozU3Eevc97S.png'
      }
      return null
    }
  } catch (error) {
    console.error("获取用户信息时发生错误:", error)
    // 设置默认用户信息
    userInfo.value = {
      name: '未登录',
      avatar: 'https://wen-gloupfive.oss-cn-hangzhou.aliyuncs.com/EzJt5vBxxozU3Eevc97S.png'
    }
    return null
  }
}

// 暴露方法给子组件调用
defineExpose({
  fetchUserInfo
})

// 监听头像更新事件
eventBus.on('avatar-updated', (response) => {
  // 更新用户信息
  fetchUserInfo()
})

// 处理菜单选择
const handleMenuSelect = (index: string) => {
  activeMenu.value = index
  router.push(index)
}

// 处理点击聊天
const handleChatClick = () => {
  router.push('/ChatView')
}

// 处理退出登录
const handleLogout = () => {
  // 这里可添加退出登录逻辑，如清除 token 等
  router.push('/login')
}

// 组件挂载前获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<template>
  <div class="header-container">
    <div class="nav-wrapper">
      <!-- 左侧区域：菜单 -->
      <el-menu
          :default-active="activeMenu"
          active-text-color="#ffc107"
          background-color="#0052cc"
          class="el-menu-demo"
          mode="horizontal"
          text-color="#fff"
          @select="handleMenuSelect"
      >
        <el-menu-item class="logo-menu-item">
          <el-icon class="logo-icon">
            <Shop/>
          </el-icon>
          <span class="logo-text">二手交易平台</span>
        </el-menu-item>
        <el-menu-item class="nav-menu-item" index="/userHome/showGoodList">热卖专区</el-menu-item>
        <el-menu-item class="nav-menu-item" index="/userHome/Layout">我的交易</el-menu-item>
        <el-menu-item class="nav-menu-item" index="/userHome/ChatView">聊天消息</el-menu-item>
        <el-menu-item class="nav-menu-item" index="/SystemNotice">系统公告</el-menu-item>
      </el-menu>

      <!-- 右侧区域：聊天消息和用户信息 -->
      <div class="right-section">

        <!-- 用户头像和名字 -->
        <div class="user-avatar-display">
          <img
              alt="用户头像"
              class="user-avatar"
              :src="userInfo.avatar"
          />
          <span class="user-name">{{ userInfo.name }}</span>
        </div>

        <!-- 下拉菜单 -->
        <el-dropdown class="user-dropdown" trigger="click">
          <div class="dropdown-trigger" role="button" @click.prevent.stop>
            <el-icon class="dropdown-icon">
              <ArrowDown/>
            </el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu align="end">
              <el-dropdown-item @click="router.push('Layout')">
                <el-icon>
                  <User/>
                </el-icon>
                <span>我的交易</span>
              </el-dropdown-item>
              <el-dropdown-item @click="router.push('/userHome/myGood')">
                <el-icon>
                  <User/>
                </el-icon>
                <span>我的商品</span>
              </el-dropdown-item>
              <el-dropdown-item @click="router.push('myFavorite')">
                <el-icon>
                  <User/>
                </el-icon>
                <span>我的收藏</span>
              </el-dropdown-item>
              <el-dropdown-item @click="router.push('profile')">
                <el-icon>
                  <User/>
                </el-icon>
                <span>个人中心</span>
              </el-dropdown-item>
              <!--              <el-dropdown-item @click="router.push('/settings')">-->
              <!--                <el-icon>-->
              <!--                  <Setting/>-->
              <!--                </el-icon>-->
              <!--                <span>账号设置</span>-->
              <!--              </el-dropdown-item>-->
              <el-dropdown-item @click="handleLogout">
                <span>退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
  <!-- 主内容区 -->
  <el-main>
    <div class="main-content-card">
      <RouterView></RouterView>
    </div>
  </el-main>
</template>


<style scoped>
.header-container {
  background-color: #0052cc;
}

.nav-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  max-width: 1200px;
  margin: 0 auto;
}

.logo-icon {
  margin-right: 5px;
}

/* 右侧区域 */
.right-section {
  display: flex;
  align-items: center;
  color: #fff;
}

/* 用户头像显示区域 */
.user-avatar-display {
  display: flex;
  align-items: center;
  padding: 0 16px;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 8px;
}

.user-name {
  font-size: 14px;
}

.user-dropdown {
  display: flex;
  align-items: center;
  padding: 0 16px;
}

.dropdown-trigger {
  display: flex;
  align-items: center;
  cursor: pointer;
  height: 60px;
}

/* 修改下拉箭头为白色 */
.dropdown-icon {
  font-size: 14px;
  color: #fff !important;
}

.el-menu--horizontal > .el-menu-item,
.el-menu--horizontal > .el-submenu {
  height: 60px !important;
  line-height: 60px !important;
}

.el-menu--horizontal {
  border-bottom: none !important;
}
</style>